<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Response;

class Operation extends Controller
{
    /**
     * 获取操作日志列表
     */
    public function getList(Request $request)
    {
        try {
            $param = $request->param();
            if ($param) {
                $params = $param['params'] ?? [];
            }

            $page = isset($params['page']) ? intval($params['page']) : 1;
            $pageSize = isset($params['page_size']) ? intval($params['page_size']) : 10;

            // 构建查询条件
            $where = ['is_deleted'=>0];

            // 操作人筛选
            if (!empty($params['username'])) {
                $where[] = ['username', 'like', '%' . $params['username'] . '%'];
            }

            // 操作模块筛选
            if (!empty($params['action'])) {
                $where[] = ['action', '=', $params['action']];
            }

            // 时间范围筛选
            if (!empty($params['start_date'])) {
                $where[] = ['create_at', '>=', $params['start_date'] . ' 00:00:00'];
            }
            if (!empty($params['end_date'])) {
                $where[] = ['create_at', '<=', $params['end_date'] . ' 23:59:59'];
            }

            // 获取总数
            $total = Db::table('system_log')
                ->where($where)
                ->count();

            // 获取分页数据
            $list = Db::table('system_log')
                ->where($where)
                ->order('create_at', 'desc')
                ->page($page, $pageSize)
                ->select();

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'current_page' => $page,
                    'page_size' => $pageSize
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '获取日志列表失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 删除操作日志
     */
    public function delete()
    {
        $id = input("id")??'';
        try {
            if (empty($id)) {
                return json([
                    'code' => 400,
                    'message' => '参数错误'
                ]);
            }

            $result = Db::table('system_log')
                ->where('id', $id)
                ->update(["is_deleted"=>1]);

            if ($result) {
                return json([
                    'code' => 200,
                    'message' => '删除成功'
                ]);
            } else {
                return json([
                    'code' => 500,
                    'message' => '删除失败'
                ]);
            }

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '删除失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 导出操作日志
     */
    public function export(Request $request)
    {
        try {
            $param = $request->param();
            if ($param) {
                $params = $param['params'] ?? [];
            }

            // 构建查询条件
            $where = [];

            if (!empty($params['username'])) {
                $where[] = ['username', 'like', '%' . $params['username'] . '%'];
            }

            if (!empty($params['action'])) {
                $where[] = ['action', '=', $params['action']];
            }

            if (!empty($params['start_date'])) {
                $where[] = ['create_at', '>=', $params['start_date'] . ' 00:00:00'];
            }
            if (!empty($params['end_date'])) {
                $where[] = ['create_at', '<=', $params['end_date'] . ' 23:59:59'];
            }

            $list = Db::table('system_log')
                ->where($where)
                ->order('create_at', 'desc')
                ->select();

            // 导出Excel
            $filename = '操作日志_' . date('YmdHis');
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
            header('Cache-Control: max-age=0');

            $excelData = "ID\t操作模块\t操作内容\t操作人\t操作IP\t创建时间\n";

            foreach ($list as $item) {
                $excelData .= $item['id'] . "\t";
                $excelData .= $item['action'] . "\t";
                $excelData .= $item['content'] . "\t";
                $excelData .= $item['username'] . "\t";
                $excelData .= $item['geoip'] . "\t";
                $excelData .= $item['create_at'] . "\n";
            }

            // 输出Excel文件
            echo mb_convert_encoding($excelData, 'GBK', 'UTF-8');
            exit;

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '导出失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取操作模块选项
     */
    public function getActionOptions()
    {
        try {
            $actions = Db::table('system_log')
                ->distinct(true)
                ->field('action')
                ->order('action')
                ->column('action');

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $actions
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '获取操作模块失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 添加操作日志（供其他模块调用）
     */
    public static function addLog($action, $content, $username = '', $geoip = '')
    {
        try {
            if (empty($username)) {
                // 从session获取用户名
                $username = session('username') ?: 'system';
            }

            if (empty($geoip)) {
                $geoip = request()->ip();
            }

            $data = [
                'action' => $action,
                'content' => $content,
                'username' => $username,
                'geoip' => $geoip,
                'create_at' => date('Y-m-d H:i:s')
            ];

            Db::name('system_log')->insert($data);

        } catch (\Exception $e) {
            // 日志记录失败不中断主流程
            \think\Log::error('操作日志记录失败：' . $e->getMessage());
        }
    }
}